package com.eflying.user.dao;

import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import com.eflying.user.bean.User;

import cn.itcast.jdbc.TxQueryRunner;

/**
 * 用户模块持久层
 * @author 礼逊
 *
 */
public class UserDao {
	private QueryRunner qr = new TxQueryRunner();
	/**
	 * 用户登录
	 * @throws SQLException 
	 * 
	 */
	public User findByNameAndPass(String username,String password) throws SQLException{
		String sql = "select * from t_user where loginname=? and loginpass = ?";
		Object[] params = {username,password};
		User user = qr.query(sql, new BeanHandler<User>(User.class),params);
		return user;
		
	}
	/**
	 * 校验用户名是否注册
	 * @throws SQLException 
	 */
	public boolean ajaxValidateLoginname(String loginname) throws SQLException{
		String sql = "select count(1) from t_user where loginname = ?";
		Number number = (Number)qr.query(sql, new ScalarHandler(),loginname);
		return (number.intValue() == 0);
	}
	
	/**
	 * 校验email是否注册
	 * @throws SQLException 
	 */
	public boolean ajaxValidateEmail(String email) throws SQLException{
		String sql = "select count(1) from t_user where email = ?";
		Number number = (Number)qr.query(sql, new ScalarHandler(),email);
		return (number.intValue() == 0);
	}
	
	/**
	 * 添加用户
	 * @throws SQLException 
	 */
	public void add(User user) throws SQLException{
		String sql = "insert into t_user values(?,?,?,?,?,?)";
		Object[] params = {
				user.getUid(),
				user.getLoginname(),
				user.getLoginpass(),
				user.getEmail(),
				user.isStatus(),
				user.getActivationCode()
				};
		qr.update(sql, params);
	}
	/**
	 * 邮件激活
	 * 通过激活码查找User
	 * @throws SQLException 
	 * 
	 */
	public User checkActivationCode(String aCode) throws SQLException{
		String sql = "select * from t_user where activationCode=?";
		return qr.query(sql, new BeanHandler<User>(User.class),aCode);
	}
	/**
	 * 如果找到对象，则进行状态位的激活
	 */
	public void updateStatus(String uid,boolean status) throws SQLException{
		String sql = "update t_user set status=? where uid=?";
		qr.update(sql,status,uid);
	}
	/**
	 * 修改密码功能(查询是否存在)
	 * @throws SQLException 
	 */
	public boolean findByUidAndPwd(String uid, String pwd) throws SQLException {
		String sql = "select count(1) from t_user where uid = ? and loginpass = ?";
		Number number = (Number) qr.query(sql, new ScalarHandler(), uid, pwd);
		return number.intValue() > 0;
	}
	/**
	 * 修改密码
	 * @throws SQLException 
	 */
	public void updatePassword(String uid,String pwd) throws SQLException{
		String sql = "update t_user set loginpass = ? where uid = ?";
		qr.update(sql,pwd,uid);
	}
}
